package io.qifan.desktop.server.application;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import io.qifan.desktop.api.auth.request.UserLoginRequest;
import io.qifan.desktop.server.domain.user.QUser;
import io.qifan.desktop.server.domain.user.User;
import io.qifan.desktop.server.domain.user.mapper.UserMapper;
import io.qifan.desktop.server.domain.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthApplicationService {

    private final UserRepository userRepository;

    /**
     * 登录和注册合在一起
     *
     * @param loginRequest 登录请求
     * @return token
     */
    public SaTokenInfo login(UserLoginRequest loginRequest) {
        log.info("登录请求：{}", loginRequest);
        // 这样用户肯定不为空
        User user = userRepository
                .findOne(QUser.user.username.eq(loginRequest.getUsername()))
                .orElseGet(() -> register(loginRequest));
        // 密码校验，先存明文
        user.checkPassword(loginRequest.getPassword());
        // 生成token
        StpUtil.login(user.getId());
        // 返回token
        return StpUtil.getTokenInfo();
    }

    private User register(UserLoginRequest loginRequest) {
        return userRepository.save(UserMapper.INSTANCE.loginRequest2User(loginRequest));
    }
}
